package org.groupg.practice;

import org.mapdb.*;
import java.util.concurrent.TimeUnit;

public class CacheWithExpirationExample {
    public static void main(String[] args) throws InterruptedException {
        DB db = DBMaker.memoryDB().make();

        // 创建带过期时间的缓存
        HTreeMap<String, String> cache = (HTreeMap<String, String>) db.hashMap("sessionCache")
                .expireAfterCreate(5, TimeUnit.SECONDS) // 5秒后过期
                .expireAfterUpdate(5, TimeUnit.SECONDS) // 更新后5秒过期
                .expireAfterGet(5, TimeUnit.SECONDS) // 访问后5秒过期
                .create();

        // 添加数据
        cache.put("session1", "user_data_1");
        cache.put("session2", "user_data_2");

        System.out.println("Immediately after adding:");
        System.out.println("Session1: " + cache.get("session1"));
        System.out.println("Session2: " + cache.get("session2"));

        // 等待6秒
        System.out.println("\nWaiting 6 seconds...");
        Thread.sleep(6000);

        System.out.println("\nAfter 6 seconds:");
        System.out.println("Session1: " + cache.get("session1")); // 应为null
        System.out.println("Session2: " + cache.get("session2")); // 应为null

        db.close();
    }
}